package rest

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/user"
	"github.com/infraboard/mcube/client/rest"
)

type Respone struct {
	Code    int           `json:"code"`
	Message *user.Session `json:"message"`
}

func NewClient(conf *Config) *Client {
	c := rest.NewRESTClient()
	c.SetBaseURL(conf.URL)
	c.SetBasicAuth(conf.Username, conf.Password)

	return &Client{
		c:    c,
		conf: conf,
	}
}

type Client struct {
	conf    *Config
	c       *rest.RESTClient
	session *user.Session
}

func (c *Client) Session() string {
	return fmt.Sprintf("username: %s, session: %s",
		c.session.UserName, c.session.Id)
}

func (c *Client) Login() error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	resp := &Respone{Message: &user.Session{}}

	err := c.c.Post("user/login").Do(ctx).Into(resp)
	if err != nil {
		return err
	}
	// 存储session
	c.session = resp.Message
	c.c.SetCookie(&http.Cookie{Name: "username", Value: resp.Message.UserName},
		&http.Cookie{Name: "session", Value: resp.Message.Id})
	return nil
}
